package com.ruoyi.system.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.domain.DataScreeningPersonnelControl;
import com.ruoyi.system.domain.DataScreeningPersonnelUav;
import com.ruoyi.system.domain.vo.req.personne.PersonneControlReqVo;
import com.ruoyi.system.domain.vo.req.personne.PersonneEditReqVo;
import com.ruoyi.system.domain.vo.req.personne.PersonneQueryReqVo;
import com.ruoyi.system.domain.vo.resp.UserInfoRespVo;
import com.ruoyi.system.domain.vo.resp.personne.PersonneCountRespVo;
import com.ruoyi.system.domain.vo.resp.personne.PersonneInfoRespVo;
import com.ruoyi.system.domain.vo.resp.personne.PersonneListRespVo;
import com.ruoyi.system.domain.vo.resp.personne.PersonneUavInfoRespVo;
import com.ruoyi.system.mapper.DataScreeningPersonnelControlMapper;
import com.ruoyi.system.mapper.DataScreeningPersonnelUavMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DataScreeningPersonnelMapper;
import com.ruoyi.system.domain.DataScreeningPersonnel;
import com.ruoyi.system.service.IDataScreeningPersonnelService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 被排查人员Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-06-25
 */
@Service
@RequiredArgsConstructor
public class DataScreeningPersonnelServiceImpl  extends ServiceImpl<DataScreeningPersonnelMapper, DataScreeningPersonnel> implements IDataScreeningPersonnelService
{
    private final DataScreeningPersonnelMapper dataScreeningPersonnelMapper;
    private final DataScreeningPersonnelUavMapper dataScreeningPersonnelUavMapper;
    private final DataScreeningPersonnelControlMapper dataScreeningPersonnelControlMapper;
    private final SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询被排查人员
     * 
     * @param screeningPersonnelId 被排查人员主键
     * @return 被排查人员
     */
    @Override
    public DataScreeningPersonnel selectDataScreeningPersonnelByScreeningPersonnelId(Long screeningPersonnelId)
    {
        return dataScreeningPersonnelMapper.selectDataScreeningPersonnelByScreeningPersonnelId(screeningPersonnelId);
    }

    /**
     * 查询被排查人员列表
     * 
     * @param dataScreeningPersonnel 被排查人员
     * @return 被排查人员
     */
    @Override
    public List<DataScreeningPersonnel> selectDataScreeningPersonnelList(DataScreeningPersonnel dataScreeningPersonnel)
    {
        return dataScreeningPersonnelMapper.selectDataScreeningPersonnelList(dataScreeningPersonnel);
    }

    /**
     * 查询被排查人员列表
     *
     * @param reqVo 被排查人员
     * @return 被排查人员
     */
    @Override
    public List<PersonneListRespVo> selectPersonneList(PersonneQueryReqVo reqVo)
    {
        //UserInfoRespVo userPost = sysUserMapper.getUserPost(SecurityUtils.getUserId());
        SysDept dept = tokenService.getLoginUser().getSysUser().getDept();
        List<PersonneListRespVo> personneListRespVos = new ArrayList<>();
        reqVo.setDeptId(dept.getDeptId());
        reqVo.setDeptLevel(dept.getDeptLevel());
//        if (3 == userPost.getDeptLevel()) {

            PageUtils.startPage();
            personneListRespVos = dataScreeningPersonnelMapper.selectPersonneList(reqVo);
//        }else if (2 == userPost.getDeptLevel()){
//            reqVo.setDeptLevel(2);
//            PageUtils.startPage();
//            personneListRespVos = dataScreeningPersonnelMapper.selectPersonneList(reqVo);
//        }else {
//            reqVo.setDeptLevel(1);
//            PageUtils.startPage();
//            personneListRespVos = dataScreeningPersonnelMapper.selectPersonneList(reqVo);
//        }
        return personneListRespVos;
    }


    /**
     * 查询被排查人员列表
     * @return 被排查人员
     */
    @Override
    public PersonneCountRespVo selectPersonneCountList()
    {
        PersonneCountRespVo personneCountRespVo = new PersonneCountRespVo();
        PersonneQueryReqVo reqVo = new PersonneQueryReqVo();
        SysDept dept = tokenService.getLoginUser().getSysUser().getDept();
        UserInfoRespVo userPost = new UserInfoRespVo();
        //UserInfoRespVo userPost = sysUserMapper.getUserPost(SecurityUtils.getUserId());
//        UserInfoRespVo userPost = new UserInfoRespVo();
        reqVo.setDeptId(dept.getDeptId());
        reqVo.setDeptLevel(dept.getDeptLevel());
//        reqVo.setDeptId(1L);
//        reqVo.setDeptLevel(1);
//        userPost.setDeptId(1L);
//        userPost.setDeptLevel(1);
        List<PersonneListRespVo> personneListRespVos = dataScreeningPersonnelMapper.selectPersonneList(reqVo);
        if (null != personneListRespVos && personneListRespVos.size() > 0){
            personneCountRespVo.setHeadcount(personneListRespVos.size());
            Integer integer = dataScreeningPersonnelMapper.selectPersonneCensusRegisterPeoList(userPost);
            List<PersonneListRespVo> residentoList = dataScreeningPersonnelMapper.selectPersonneResidentoList(userPost);
            personneCountRespVo.setResident(residentoList.size());
            personneCountRespVo.setCensusRegisterPeo(integer);
            personneCountRespVo.setHeadHold(dataScreeningPersonnelMapper.selectUavSum(userPost,null));
            DecimalFormat df = new DecimalFormat("#.##");
            if (Objects.nonNull(personneCountRespVo.getHeadHold()) && Objects.nonNull(personneCountRespVo.getHeadcount())) {
//                Integer result = personneCountRespVo.getHeadHold() / personneCountRespVo.getHeadcount();
//            personneCountRespVo.setHeadAverageHold(dataScreeningPersonnelMapper.selectUavAvgCount(userPost.getDeptId(),null));
//                personneCountRespVo.setHeadAverageHold(Integer.valueOf(df.format(result)));
                personneCountRespVo.setHeadAverageHold(0.0);
                if(personneCountRespVo.getHeadHold() != 0){
                    double result = (double) personneCountRespVo.getHeadHold() / personneCountRespVo.getHeadcount();
                    String formattedResult = df.format(result);
                    personneCountRespVo.setHeadAverageHold(Double.valueOf(formattedResult));
                }

            }
            reqVo.setPersonnelType(1);
            List<PersonneListRespVo> keyPersonnelRespVos = dataScreeningPersonnelMapper.selectPersonneList(reqVo);
            if (null != personneListRespVos && personneListRespVos.size() > 0){
                personneCountRespVo.setKeyPersonnel(keyPersonnelRespVos.size());
                PersonneQueryReqVo controlled = new PersonneQueryReqVo();
                controlled.setDeptId(userPost.getDeptId());
                controlled.setPersonnelType(1);
                controlled.setControlType(3);
                personneCountRespVo.setControlled(dataScreeningPersonnelMapper.selectPersonneList(controlled).size());
                PersonneQueryReqVo goldieLock = new PersonneQueryReqVo();
                goldieLock.setDeptId(userPost.getDeptId());
                goldieLock.setPersonnelType(1);
                goldieLock.setControlType(2);
                personneCountRespVo.setGoldieLock(dataScreeningPersonnelMapper.selectPersonneList(goldieLock).size());
                personneCountRespVo.setKeyHold(dataScreeningPersonnelMapper.selectUavSum(userPost,1));
                if (Objects.nonNull(personneCountRespVo.getKeyHold()) && Objects.nonNull(personneCountRespVo.getKeyPersonnel())) {
//                    Integer keyResult = personneCountRespVo.getKeyHold() / personneCountRespVo.getKeyPersonnel();

                    personneCountRespVo.setKeyAverageHold(0.0);
                    if(personneCountRespVo.getKeyHold() != 0){
                        double result = (double) personneCountRespVo.getKeyHold() / personneCountRespVo.getKeyPersonnel();
                        String formattedResult = df.format(result);
                        personneCountRespVo.setKeyAverageHold(Double.valueOf(formattedResult));
                    }

//                    personneCountRespVo.setHeadAverageHold(Double.valueOf(formattedResult));
                }
//            personneCountRespVo.setHeadAverageHold(dataScreeningPersonnelMapper.selectUavAvgCount(userPost.getDeptId(),null));

//                personneCountRespVo.setKeyAverageHold(dataScreeningPersonnelMapper.selectUavAvgCount(userPost.getDeptId(),1));
            }
        }
        return personneCountRespVo;
    }

    /**
     * 查询被排查人员详情
     *
     * @param screeningPersonnelId 被排查人员
     * @return 被排查人员
     */
    @Override
    public PersonneInfoRespVo selectPersonneListById(Long screeningPersonnelId)
    {
        PersonneInfoRespVo personneInfoRespVo = dataScreeningPersonnelMapper.selectPersonneListById(screeningPersonnelId);
        if (Objects.isNull(personneInfoRespVo)){
            return null;
        }
        List<PersonneUavInfoRespVo> personneUavInfoRespVos = dataScreeningPersonnelMapper.selectUavListById(screeningPersonnelId);
        if (null != personneUavInfoRespVos && personneUavInfoRespVos.size() > 0){
            personneInfoRespVo.setUavCount(personneUavInfoRespVos.size());
            personneInfoRespVo.setPersonneUavInfoRespVos(personneUavInfoRespVos);
        }
        return personneInfoRespVo;
    }

    /**
     * 新增被排查人员
     * 
     * @param dataScreeningPersonnel 被排查人员
     * @return 结果
     */
    @Override
    public int insertDataScreeningPersonnel(DataScreeningPersonnel dataScreeningPersonnel)
    {
        dataScreeningPersonnel.setCreateTime(DateUtils.getNowDate());
        return dataScreeningPersonnelMapper.insertDataScreeningPersonnel(dataScreeningPersonnel);
    }

    /**
     * 修改被排查人员
     * 
     * @param reqVo 被排查人员
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateDataScreeningPersonnel(PersonneEditReqVo reqVo)
    {
        DataScreeningPersonnel dataScreeningPersonnel = new DataScreeningPersonnel();
        BeanUtils.copyProperties(reqVo,dataScreeningPersonnel);
        dataScreeningPersonnel.setDeptId(reqVo.getPoliceId());
        if (null == reqVo.getLocalPoliceStation() || ("").equals(reqVo.getLocalPoliceStation())) {
            dataScreeningPersonnel.setLocalPoliceStation(reqVo.getLocalPoliceStation());
        } else {
            dataScreeningPersonnel.setLocalPoliceStationId(null);
        }
        dataScreeningPersonnel.setUpdateUser(SecurityUtils.getUserId());
        int insert = dataScreeningPersonnelMapper.update(dataScreeningPersonnel,new LambdaQueryWrapper<DataScreeningPersonnel>()
                .eq(DataScreeningPersonnel::getScreeningPersonnelId,reqVo.getScreeningPersonnelId())
                .eq(DataScreeningPersonnel::getStatus,0));
        insterUav(reqVo.getPersonneUavInfoRespVos(), reqVo.getScreeningPersonnelId());
        return insert;
    }

    /**
     * 修改被排查人员
     *
     * @param reqVo 被排查人员
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int control(PersonneControlReqVo reqVo)
    {
        int update = 0;
        DataScreeningPersonnelControl dataScreeningPersonnelControl = new DataScreeningPersonnelControl();
        BeanUtils.copyProperties(reqVo,dataScreeningPersonnelControl);
        if (null != reqVo.getControlId()) {
            DataScreeningPersonnel dataScreeningPersonnel = new DataScreeningPersonnel();
            dataScreeningPersonnel.setScreeningPersonnelId(reqVo.getScreeningPersonnelId());
            dataScreeningPersonnel.setControlType(3);
            dataScreeningPersonnelMapper.updateById(dataScreeningPersonnel);
            dataScreeningPersonnelControl.setUpdateUser(SecurityUtils.getUserId());
            update = dataScreeningPersonnelControlMapper.updateById(dataScreeningPersonnelControl);
        }else {
            dataScreeningPersonnelControl.setUpdateUser(SecurityUtils.getUserId());
            dataScreeningPersonnelControl.setCreateUser(SecurityUtils.getUserId());
            update = dataScreeningPersonnelControlMapper.insert(dataScreeningPersonnelControl);
        }
        DataScreeningPersonnel dataScreeningPersonnel = new DataScreeningPersonnel();
        BeanUtils.copyProperties(reqVo,dataScreeningPersonnel);
        dataScreeningPersonnel.setScreeningPersonnelId(reqVo.getScreeningPersonnelId());
        dataScreeningPersonnel.setControlType(3);
        dataScreeningPersonnel.setUpdateUser(SecurityUtils.getUserId());
        dataScreeningPersonnelMapper.updateById(dataScreeningPersonnel);
        return update;
    }

    private void insterUav(List<PersonneUavInfoRespVo> personneUavInfoRespVos,Long screeningPersonnelId){
        DataScreeningPersonnelUav screeningPersonnelUav = new DataScreeningPersonnelUav();
        screeningPersonnelUav.setStatus(1);
        screeningPersonnelUav.setUpdateUser(SecurityUtils.getUserId());
        int update = dataScreeningPersonnelUavMapper.update(screeningPersonnelUav, new LambdaQueryWrapper<DataScreeningPersonnelUav>()
                .eq(DataScreeningPersonnelUav::getScreeningPersonnelId,screeningPersonnelId)
                .eq(DataScreeningPersonnelUav::getStatus,0));
        personneUavInfoRespVos.forEach(personneUavInfoRespVo -> {
            DataScreeningPersonnelUav dataScreeningPersonnelUav = new DataScreeningPersonnelUav();
            BeanUtils.copyProperties(personneUavInfoRespVo,dataScreeningPersonnelUav);
            dataScreeningPersonnelUav.setScreeningPersonnelId(screeningPersonnelId);
            dataScreeningPersonnelUav.setCreateUser(SecurityUtils.getUserId());
            dataScreeningPersonnelUavMapper.insert(dataScreeningPersonnelUav);
        });
    }

    /**
     * 批量删除被排查人员
     * 
     * @param screeningPersonnelIds 需要删除的被排查人员主键
     * @return 结果
     */
    @Override
    public int deleteDataScreeningPersonnelByScreeningPersonnelIds(Long[] screeningPersonnelIds)
    {
        return dataScreeningPersonnelMapper.deleteDataScreeningPersonnelByScreeningPersonnelIds(screeningPersonnelIds);
    }

    /**
     * 删除被排查人员信息
     * 
     * @param screeningPersonnelId 被排查人员主键
     * @return 结果
     */
    @Override
    public int deleteDataScreeningPersonnelByScreeningPersonnelId(Long screeningPersonnelId)
    {
        return dataScreeningPersonnelMapper.deleteDataScreeningPersonnelByScreeningPersonnelId(screeningPersonnelId);
    }
}
